package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @Author FengHuan Wang
 * @Date 2024/12/29 16:27
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/admin/dish")
@Api("菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    /*新增菜品功能实现*/
    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("开始添加菜品");
        dishService.save(dishDTO);
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    /*菜品分页查询功能实现*/
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO){
        log.info("开始菜品分页查询");
        PageResult pageResult =  dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /*根据id来删除菜品*/
    @DeleteMapping
    @ApiOperation("根据id批量删除菜品")
    public Result deleteById(@RequestParam List<Long> ids){
        log.info("开始批量删除菜品");
        dishService.deleteById(ids);
        cleanCache("dish_*");
        return Result.success();
    }

    /*修改菜品功能实现-查询回显*/
    @GetMapping("/{dishId}")
    @ApiOperation("查询回显")
    public Result<DishVO> getById(@PathVariable Long dishId){
        log.info("开始菜品查询回显");
        DishVO dishVO =  dishService.getById(dishId);
        return Result.success(dishVO);
    }

    /*根据id修改菜品功能实现*/
    @PutMapping
    public Result updateDishById(@RequestBody DishVO dishVO){
        log.info("开始修改菜品");
        dishService.updateDishById(dishVO);
        cleanCache("dish_*");
        return Result.success();
    }

    /*根据分类id查询菜品*/
    @GetMapping("/list")
    @ApiOperation("根据分类ID查询菜品")
    public Result<List<Dish>> getByCategoryId(Long categoryId){
        log.info("开始根据分类id查询菜品");
         List<Dish> dish =  dishService.getByCategoryId(categoryId);
        return Result.success(dish);
    }

    /*菜品起售停售功能实现*/
    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售停售接口")
    public Result stopAndStart(@PathVariable Integer status,Long id){
        dishService.stopAndStop(status,id);
        cleanCache("dish_*");
        return Result.success();
    }

    /*清理缓存数据*/
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
